package com.transportation.app.net

import android.util.Log
import com.blankj.utilcode.util.DeviceUtils
import com.transportation.app.App
import com.transportation.app.utils.AppUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * retrofit 管理器
 */
object RetrofitManager {

    private var retrofit: Retrofit? = null
    fun retrofit(): Retrofit {
        if (retrofit == null) {
            val logInterceptor = HttpLoggingInterceptor { message ->
                Log.d("retrofit", message)
            }.apply {
                level = HttpLoggingInterceptor.Level.BODY
            }
            val httpClient = OkHttpClient.Builder()
                .addInterceptor(logInterceptor)
                .addInterceptor(Interceptor { chain ->
                    val request = chain.request().newBuilder()
                        .addHeader("Accept", "application/json")
                        .addHeader("platform", "android")
                        .addHeader("DeviceId", DeviceUtils.getUniqueDeviceId())
                        .addHeader("versionCode", AppUtils.getAppVersionCode(App.getContext()))
                        .build()
                    chain.proceed(request)
                })
                .connectTimeout(10 * 1000, TimeUnit.MILLISECONDS)
                .build()
            retrofit = Retrofit.Builder()
                .baseUrl("https://wx-api.gpollo.com/")
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build()
        }
        return retrofit!!
    }

    /**
     * 获取接口Api interface
     */
    inline fun <reified T> api(): T {
        return retrofit().create(T::class.java)
    }

}